package cn.flying.base.security.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.base.common.enums.RtCodeEnum;
import cn.flying.base.common.vo.Rt;

/**
 * @description: 正常session过期策略，或者服务重启导致session不可用
 * @author: lvyong
 * @date: 2023年06月02日 22:03
 * @version: 1.0
 */
@Component
public class SessionInvalidStrategy implements InvalidSessionStrategy {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        logger.info("当前登录已失效，请重新登录！");
        //判断请求类型，根据不同的类型返回
        String xmlHttpRequest = "XMLHttpRequest";
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase(xmlHttpRequest)) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(Rt.error(RtCodeEnum.R10017)));
            out.flush();
            out.close();
        } else {
            //访问页面的直接跳转到登录页面
            new DefaultRedirectStrategy().sendRedirect(request, response, "/login");
        }
    }
}
